package com.byzk.p2p.front.controller;

import java.io.Serializable;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.byzk.p2p.admin.bank.dto.Bank;
import com.byzk.p2p.admin.bank.dto.BankCard;
import com.byzk.p2p.admin.bank.service.BankCardService;
import com.byzk.p2p.admin.bank.vo.BankCardVo;
import com.byzk.p2p.admin.base.controller.BaseController;
import com.byzk.p2p.admin.base.util.BaseUtil;
import com.byzk.p2p.admin.base.util.DateUtils;
import com.byzk.p2p.admin.base.util.JsonMsg;
import com.byzk.p2p.admin.base.util.MD5;
import com.byzk.p2p.admin.base.util.PageInfo;
import com.byzk.p2p.admin.base.util.SHA;
import com.byzk.p2p.admin.borrow.dao.ChangeDao;
import com.byzk.p2p.admin.borrow.dto.Change;
import com.byzk.p2p.admin.borrow.dto.Product;
import com.byzk.p2p.admin.borrow.dto.UserTender;
import com.byzk.p2p.admin.borrow.service.BorrowService;
import com.byzk.p2p.admin.borrow.service.ChangeService;
import com.byzk.p2p.admin.borrow.service.ProductService;
import com.byzk.p2p.admin.borrow.service.TenderService;
import com.byzk.p2p.admin.borrow.vo.AllowChangeVo;
import com.byzk.p2p.admin.borrow.vo.BorrowTempVo;
import com.byzk.p2p.admin.borrow.vo.BorrowTenderVo;
import com.byzk.p2p.admin.borrow.vo.ChangeVo;
import com.byzk.p2p.admin.borrow.vo.MyChangeVo;
import com.byzk.p2p.admin.borrow.vo.SalingChangeVo;
import com.byzk.p2p.admin.borrow.vo.UserTenderVo;
import com.byzk.p2p.admin.city.dto.City;
import com.byzk.p2p.admin.city.service.CityService;
import com.byzk.p2p.admin.fuiou.controller.FuionAccountController;
import com.byzk.p2p.admin.money.dto.BorrowPaymentDetail;
import com.byzk.p2p.admin.money.dto.WithdrawRecord;
import com.byzk.p2p.admin.money.service.BorrowPaymentDetailService;
import com.byzk.p2p.admin.money.service.FundRecordService;
import com.byzk.p2p.admin.money.service.RechargeService;
import com.byzk.p2p.admin.money.service.WithdrawService;
import com.byzk.p2p.admin.money.util.BaofuUtil;
import com.byzk.p2p.admin.money.util.FundRecordType;
import com.byzk.p2p.admin.money.util.FundRecordTypeVo;
import com.byzk.p2p.admin.money.vo.BorrowPaymentDetailVo;
import com.byzk.p2p.admin.money.vo.FundDetailVo;
import com.byzk.p2p.admin.money.vo.FundRecordUserVo;
import com.byzk.p2p.admin.money.vo.RechargeRecordVo;
import com.byzk.p2p.admin.money.vo.SumMoneyVo;
import com.byzk.p2p.admin.money.vo.WithdrawRecordVo;
import com.byzk.p2p.admin.order.service.OrderService;
import com.byzk.p2p.admin.order.vo.TenderOrderVo;
import com.byzk.p2p.admin.score.service.ScoreRecordService;
import com.byzk.p2p.admin.score.vo.ScoreRecordVo;
import com.byzk.p2p.admin.system.dto.MemberLevel;
import com.byzk.p2p.admin.system.service.GoodBuyService;
import com.byzk.p2p.admin.system.service.MemberService;
import com.byzk.p2p.admin.system.vo.GoodBuyVo;
import com.byzk.p2p.admin.user.dto.CneeInfo;
import com.byzk.p2p.admin.user.dto.User;
import com.byzk.p2p.admin.user.dto.UserAccount;
import com.byzk.p2p.admin.user.dto.UserAuth;
import com.byzk.p2p.admin.user.dto.UserDetailInfoAuth;
import com.byzk.p2p.admin.user.dto.UserWorkInfoAuth;
import com.byzk.p2p.admin.user.service.CneeInfoServise;
import com.byzk.p2p.admin.user.service.InviteInfoService;
import com.byzk.p2p.admin.user.service.UserAccountService;
import com.byzk.p2p.admin.user.service.UserAuthService;
import com.byzk.p2p.admin.user.service.UserService;
import com.byzk.p2p.admin.user.vo.InviteRefVo;
import com.byzk.p2p.admin.user.vo.UserAccountVo;
import com.byzk.p2p.front.service.FrontUserService;
import com.byzk.p2p.front.session.UserSession;


/**
 * 账户中心
 * @author suker.zhou
 *
 */

@Controller
@RequestMapping("/account")
@Scope("prototype")
public class FrontAccountController extends BaseController implements Serializable{

	private static final long serialVersionUID = 1L;
	
	@Autowired
	private UserAccountService accountService;
	@Autowired
	private UserAuthService authService;
	@Autowired
	private TenderService tenderService;
	@Autowired
	private BorrowService borrowService;
	@Autowired
	private UserAuthService userAuthService;
	@Autowired
	private BankCardService bankCardService;
	@Autowired
	private FundRecordService fundRecordService;
	@Autowired
	private WithdrawService withdrawService;
	@Autowired
	private ChangeService changeService;
	@Autowired
	private UserService userService;
	@Autowired
	private CityService cityService;
	
	
	@Autowired
	private RechargeService rechargeService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private ScoreRecordService scoreRecordService;
	@Autowired
	private FrontUserService frontUserService;
	@Autowired
	private GoodBuyService goodBuyService;
	@Autowired
	private CneeInfoServise cneeInfoServise;
	@Autowired
	private BorrowPaymentDetailService borrowPaymentDetailService;
	@Autowired
	private ProductService productService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private InviteInfoService inviteInfoservice;
	@Autowired
	private FuionAccountController fuionAccountController;
	
	@Autowired
	private ChangeDao changeDao;
	/**
	 * 账户中心
	 * @param pErrMsg 开户回调提示信息
	 * @return
	 */
	@RequestMapping("/info")
	public ModelAndView info(Model model){
		User user = UserSession.get();
		user=userService.getById(user.getId());
		user = userService.getById(user == null ?0:user.getId());
		//用户账户详情
		UserAccount account=accountService.getByUserId(user.getId());
		model.addAttribute("account",account);
		//用户认证情况
		HashMap<String,Integer> authMap=authService.getUserAuthDetail(user.getId());
		model.addAttribute("authMap",authMap);
		
		MemberLevel level=memberService.getById(account.getLevel());
		
		//投标记录
/*		UserTenderVo userTenderVo = new UserTenderVo();
		userTenderVo.setUserId(user.getId());
		List<BorrowTenderVo> tenderList=tenderService.getTenderByVo(userTenderVo);
		model.addAttribute("tenderList",tenderList);*/
		//贷款记录
/*		List<BorrowTempVo> borrowList=borrowService.getBorrowVoByUid(user.getId());
		model.addAttribute("borrowList",borrowList);*/

		
		FundDetailVo detail=tenderService.getFundDetailVo(user.getId());
		model.addAttribute("detail",detail);

		//累计投资金额
		Double sumTenderAmount=tenderService.sumTenderAmount(user.getId());
		model.addAttribute("sumTenderAmount",sumTenderAmount);
		//赚取收益
		Double sumTenderInterest=tenderService.sumTenderInterest(user.getId());
		Double sumTenderChangeInterest=tenderService.sumChangeTenderInterest(user.getId());
		
		model.addAttribute("sumTenderInterest",sumTenderInterest+sumTenderChangeInterest);
		
		//近3笔待收
		List<BorrowPaymentDetailVo> awaitList=borrowPaymentDetailService.lastAwaitBorrow(user.getId(),3);
		model.addAttribute("awaitList",awaitList);
		
		//检验是否承接了标
		Map<String,Object> queryMap = new HashMap<String,Object>();
		queryMap.put("start",0);
		queryMap.put("limit",20);
		List<ChangeVo> changelist = changeDao.listChange(queryMap);
		int count = changelist.size();
		model.addAttribute("count", count);
		if(changelist!=null && changelist.size()>0){
			for(ChangeVo item : changelist){
				if(user.getId().equals(item.getChangeUserId())){
					//承接了标的代收
					List<BorrowPaymentDetailVo> awaichangetList = borrowPaymentDetailService.lastAwaitChangeBorrow(item.getUserId(), 3);
					model.addAttribute("awaiteChaneList",awaichangetList);
				}
			}
		}
		
		model.addAttribute("awaitList", awaitList);
		model.addAttribute("user", user);

		model.addAttribute("level", level);

		return new ModelAndView("/front/account/info1");
	}
	
	/**
	 * 资金记录页面
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/fund",method=RequestMethod.GET)
	public ModelAndView funds(Model model,
			@RequestParam(value="index",required=false,defaultValue="1") int index,
			@RequestParam(value="limit",required=false,defaultValue="10") int limit,
			@RequestParam(value = "publishTimeBegin",required = false)String publishTimeBegin,
			@RequestParam(value = "publishTimeEnd",required = false)String publishTimeEnd,
			@RequestParam(value = "type",required = false,defaultValue="-1")Integer type,
			@RequestParam(value="timePeriod",required=false,defaultValue="-1")String timePeriod) throws Exception{
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		UserAccountVo userAccountVo = accountService.getAccountVoByUserId(user.getId());
		//资金总额	可用余额	冻结余额	待收总额	充值总额	提现总额	可用授信
		//时间	类型	收入	支出	可用余额	冻结余额	备注
		FundRecordUserVo fundRecordUserVo = new FundRecordUserVo();
		fundRecordUserVo.setIndex(index);
		fundRecordUserVo.setLimit(limit);
		if(!"-1".equals(timePeriod)) {
			fundRecordUserVo.setTimePeriod(timePeriod);
			model.addAttribute("timePeriod", timePeriod);
		}
		if (StringUtils.isNotBlank(publishTimeBegin)) {
			fundRecordUserVo.setPublishTimeStart(DateUtils.getRealDate(DateUtils.convert(publishTimeBegin, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
		}
		if (StringUtils.isNotBlank(publishTimeEnd)) {
			fundRecordUserVo.setPublishTimeEnd(DateUtils.getFullDate(DateUtils.convert(publishTimeEnd, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
		}
		if (type != -1) {
			fundRecordUserVo.setType(type);
		}
		fundRecordUserVo.setUserId(user.getId());
		PageInfo<FundRecordUserVo> pageInfo = fundRecordService.list(fundRecordUserVo);
		FundDetailVo detail=tenderService.getFundDetailVo(user.getId());
		model.addAttribute("publishTimeBegin", publishTimeBegin);
		model.addAttribute("publishTimeEnd", publishTimeEnd);
		model.addAttribute("type", type);
		model.addAttribute("detail",detail);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("account", userAccountVo);
		model.addAttribute("total", pageInfo.getTotal());
		List<FundRecordTypeVo> typeList=FundRecordType.toList(FundRecordType.Type.values());
		model.addAttribute("typeList", typeList);
		return new ModelAndView("/front/account/funds1");
	}
	
	/**
	 * 充值记录页面
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/recharge/record")
	public ModelAndView rechargeRecords(Model model,
				@RequestParam(value="index",required=false,defaultValue="1") int index,
				@RequestParam(value="limit",required=false,defaultValue="10") int limit,
				@RequestParam(value = "publishTimeBegin",required = false)String publishTimeBegin,
				@RequestParam(value = "publishTimeEnd",required = false)String publishTimeEnd) throws Exception{
		User user =UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		if (user == null) {
			session.removeAttribute("_user");
			return new ModelAndView("/login");
		}
		RechargeRecordVo rechargeRecordVo = new RechargeRecordVo();
		rechargeRecordVo.setIndex(index);
		rechargeRecordVo.setLimit(limit);
		if (StringUtils.isNotBlank(publishTimeBegin)) {
			rechargeRecordVo.setPublishTimeStart(DateUtils.getRealDate(DateUtils.convert(publishTimeBegin, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
		}
		if (StringUtils.isNotBlank(publishTimeEnd)) {
			rechargeRecordVo.setPublishTimeEnd(DateUtils.getFullDate(DateUtils.convert(publishTimeEnd, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
		}
		rechargeRecordVo.setUserId(user.getId());
		PageInfo<RechargeRecordVo> pageInfo = rechargeService.listByMethod(rechargeRecordVo);
		model.addAttribute("publishTimeBegin", publishTimeBegin);
		model.addAttribute("publishTimeEnd", publishTimeEnd);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("total", pageInfo.getTotal());
		model.addAttribute("type", "records");
		return new ModelAndView("/front/account/recharge_records1");
	}
	
	/**
	 * 提现记录
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/withdraw/record", method = RequestMethod.GET)
	public ModelAndView withdrawRecords(Model model,
					@RequestParam(value="index",required=false,defaultValue="1") int index,
					@RequestParam(value="limit",required=false,defaultValue="10") int limit,
					@RequestParam(value = "publishTimeBegin",required = false)String publishTimeBegin,
					@RequestParam(value = "publishTimeEnd",required = false)String publishTimeEnd,
					@RequestParam(value = "type",required = false,defaultValue="withdraw")String type) throws Exception{
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		if (user == null) {
			session.removeAttribute("_user");
			return new ModelAndView("/login");
		}
		if("records".equals(type)){
			WithdrawRecordVo withdrawRecordVo = new WithdrawRecordVo();
			withdrawRecordVo.setIndex(index);
			withdrawRecordVo.setLimit(limit);
			if (StringUtils.isNotBlank(publishTimeBegin)) {
				withdrawRecordVo.setPublishTimeStart(DateUtils.getRealDate(DateUtils.convert(publishTimeBegin, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			}
			if (StringUtils.isNotBlank(publishTimeEnd)) {
				withdrawRecordVo.setPublishTimeEnd(DateUtils.getFullDate(DateUtils.convert(publishTimeEnd, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			}
			withdrawRecordVo.setUserId(user.getId());
			PageInfo<WithdrawRecordVo> pageInfo = withdrawService.listWithdrawByStatus(withdrawRecordVo);
//			提现银行	提现账号	提现总额（元）	到账金额（元）	手续费（元）	提现时间	状态	操作	备注
			model.addAttribute("publishTimeBegin", publishTimeBegin);
			model.addAttribute("publishTimeEnd", publishTimeEnd);
			model.addAttribute("pageInfo", pageInfo);
		}
		model.addAttribute("type", type);
		return new ModelAndView("/front/account/withdraw_records1");
	}
	
	/**
	 * 我的投资
	 * @param status 借款标状态
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/invest", method = RequestMethod.GET)
	public ModelAndView investment(Model model,
					@RequestParam(value="index",required=false,defaultValue="1") int index,
					@RequestParam(value="limit",required=false,defaultValue="10") int limit,
					@RequestParam(value="status",required=false,defaultValue="pay")String status,
					@RequestParam(value = "publishTimeBegin",required = false)String publishTimeBegin,
					@RequestParam(value = "publishTimeEnd",required = false)String publishTimeEnd,
					@RequestParam(value="timePeriod",required=false,defaultValue="-1")String timePeriod) throws Exception{
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		if (user == null) {
		session.removeAttribute("frontUser");
		return new ModelAndView("/front/user/login");
		}
		//投资中的贷款
		UserTenderVo tender = new UserTenderVo();
		tender.setIndex(index);
		tender.setLimit(limit);
		if(status == "borrow"){
			tender.setTenderIngStatus("Y");
		}else{
			tender.setStatus(status);
		}
		if (StringUtils.isNotBlank(publishTimeBegin)) {
			tender.setCreateTimeBegin(DateUtils.getRealDate(DateUtils.convert(publishTimeBegin, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			model.addAttribute("publishTimeBegin", publishTimeBegin);
		}
		if (StringUtils.isNotBlank(publishTimeEnd)) {
			tender.setCreateTimeEnd(DateUtils.getFullDate(DateUtils.convert(publishTimeEnd, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			model.addAttribute("publishTimeEnd", publishTimeEnd);
		}
		tender.setTimePeriod(timePeriod);
		tender.setUserId(user.getId());
		PageInfo<BorrowTenderVo> pageInfo = tenderService.getUserTender(tender);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("total", pageInfo.getTotal());
		model.addAttribute("status", status);
		model.addAttribute("timePeriod", timePeriod);
		return new ModelAndView("/front/account/invest1");
	}
	
	/**
	 * 债权转让
	 * @return
	 */
	@RequestMapping(value="/change", method = RequestMethod.GET)
	public ModelAndView change(Model model,
			@RequestParam(value="index",required=false,defaultValue="1") int index,
			@RequestParam(value="limit",required=false,defaultValue="10") int limit,
			@RequestParam(value="temp",required=false,defaultValue="1") Integer temp){
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		if(1 == temp){
			//可转让的债权
			UserTender tender = new UserTender();
			tender.setIndex(index);
			tender.setLimit(limit);
			tender.setRepayFinish("N");
			tender.setUserId(user.getId());
			PageInfo<AllowChangeVo> allowPageInfo=tenderService.listAllowChange(tender);
			model.addAttribute("allowPageInfo", allowPageInfo);
		}else if(2 == temp){
			//承接的债权
			Change change = new Change();
			change.setChangeUserId(user.getId());
			change.setIndex(index);
			change.setLimit(limit);
			PageInfo<MyChangeVo> myChangePageInfo=changeService.listByChangeUserId(change);
			model.addAttribute("myChangePageInfo", myChangePageInfo);
		}else if(3 == temp){
			//出售中的债权
			UserTender tender = new UserTender();
			tender.setIndex(index);
			tender.setLimit(limit);
			tender.setUserId(user.getId());
			PageInfo<SalingChangeVo> salingPageInfo=tenderService.listSalingChange(tender);
			model.addAttribute("salingPageInfo", salingPageInfo);
		}
		//回收中的债权
		//List<AllowChangeVo> repayList=tenderService.listAllowChange("N",user.getId());
		//已出售的债权
		//List<MySaleChangeVo> saleList=tenderService.listMySaleChange(user.getId());
		model.addAttribute("temp", temp);
		return new ModelAndView("/front/account/change1");
	}
	
	/**
	 * 取消转让
	 * @param changeId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/change/cancel")
	public String changeCancel(@RequestParam(value="changeId",required=false) Integer changeId) throws Exception {
		if(changeId == null) {
			super.printJSON(new JsonMsg(1, "该转让信息不存在"));
			return null;
		}
		Change change = changeService.getById(changeId);
		if(change == null) {
			super.printJSON(new JsonMsg(1, "该转让信息不存在"));
			return null;
		}
		if(!"T".equals(change.getStatus())){
			super.printJSON(new JsonMsg(1, "只有未完成的转让可以取消"));
			return null;
		}
		change.setStatus("N");
		int item = changeService.saveOrUpdateChange(change);
		if(item>0) {
			super.printJSON(new JsonMsg(-1, "取消转让成功"));
		}else {
			super.printJSON(new JsonMsg(1, "取消转让失败"));
		}
		return null;
	}
	/**
	 * 自动投标
	 * @return
	 */
	@RequestMapping("/auto")
	public ModelAndView autoBid(Model model){
		String respCode = request.getParameter("RespCode");
		System.out.println(respCode);
		ModelAndView modelAndView = new ModelAndView();
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		//用户账户
		UserAccountVo userAccountVo = accountService.getAccountVoByUserId(user.getId());
		//自动投标设置
		TenderOrderVo tenderOrderVo =  orderService.selectByUserId(user.getId());
		//自动投标记录
		UserTenderVo userTenderVo = new UserTenderVo();
		userTenderVo.setIndex(1);
		userTenderVo.setLimit(10);
		userTenderVo.setUserId(user.getId());
		userTenderVo.setIsAuto("Y");
		PageInfo<BorrowTenderVo> pageInfo = tenderService.getUserTender(userTenderVo);
		modelAndView.addObject("account", userAccountVo);
		modelAndView.addObject("auto", tenderOrderVo);
		modelAndView.addObject("pageInfo", pageInfo);
		modelAndView.addObject("total", pageInfo.getTotal());
		modelAndView.setViewName("/front/account/auto1");  
		return modelAndView;
	}
	
	/**
	 * 我的积分
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/score", method = RequestMethod.GET)
	public ModelAndView pointRecords(Model model,
						@RequestParam(value="index",required=false,defaultValue="1") int index,
						@RequestParam(value="limit",required=false,defaultValue="10") int limit,
						@RequestParam(value = "startTime",required = false)String startTime,
						@RequestParam(value = "endTime",required = false)String endTime,
						@RequestParam(value = "type",required = false)String type,
						@RequestParam(value="temp",required=false,defaultValue="record") String temp) throws Exception{
		//筛选： 历史时间开始--时间结束  类型
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		ScoreRecordVo scoreRecordVo = new ScoreRecordVo();
		scoreRecordVo.setUserId(user.getId());
		if("record".equals(temp)){
			//积分记录
			ScoreRecordVo score = scoreRecordService.scoreRecord(scoreRecordVo);
			model.addAttribute("score", score);
			ScoreRecordVo vo = new ScoreRecordVo();
			if (StringUtils.isNotBlank(startTime)) {
				vo.setStartTime(DateUtils.getRealDate(DateUtils.convert(startTime, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			}
			if (StringUtils.isNotBlank(endTime)) {
				vo.setEndTime(DateUtils.getFullDate(DateUtils.convert(endTime, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			}
			if (StringUtils.isNotBlank(type)) {
				vo.setOptType(type);
			}
			vo.setUserId(user.getId());
			vo.setIndex(index);
			vo.setLimit(limit);
			PageInfo<ScoreRecordVo> pageInfo = scoreRecordService.listScoreRecord(vo);
			model.addAttribute("pageInfo",pageInfo);
		}else if("convert".equals(temp)){
			//我的兑换
			GoodBuyVo info = new GoodBuyVo();
			info.setUserId(user.getId());
			info.setIndex(index);
			info.setLimit(limit);
			if (StringUtils.isNotBlank(startTime)) {
				info.setStartTime(DateUtils.getRealDate(DateUtils.convert(startTime, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			}
			if (StringUtils.isNotBlank(endTime)) {
				info.setEndTime(DateUtils.getFullDate(DateUtils.convert(endTime, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			}
			PageInfo<GoodBuyVo> buyPageInfo = goodBuyService.listGoodBuy(info);
			model.addAttribute("buyPageInfo",buyPageInfo);
		}else if("address".equals(temp)){
			//收获地址
			CneeInfo info = new  CneeInfo();
			info.setUserId(user.getId());
			info.setIndex(index);
			info.setLimit(limit);
			PageInfo<CneeInfo> cnee = cneeInfoServise.listCnee(info);
			model.addAttribute("cnee",cnee);
		}
		model.addAttribute("type", type);
		model.addAttribute("startTime", startTime);
		model.addAttribute("endTime", endTime);
		model.addAttribute("temp",temp);
		return new ModelAndView("/front/account/score1");
	}

	/**
	 * 积分兑换
	 * @return
	 */
	@RequestMapping(value="/score/exchange", method = RequestMethod.GET)
	public ModelAndView redeem(Model model){
		return new ModelAndView("/front/account/score_exchange");
	}
	
	/**
	 * 分页查询积分查询
	 * @param score
	 * @param sTime
	 * @param eTime
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/points/list" , method=RequestMethod.POST)
	public void score(
				@RequestParam(value="index",required=false,defaultValue="1") int index,
			    @RequestParam(value="limit",required=false,defaultValue="10") int limit,
				@RequestParam(value="optType",required=false) String optType ,
				@RequestParam(value="sTime",required=false) String sTime,
				@RequestParam(value="eTime",required=false) String eTime) throws Exception{
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		ScoreRecordVo scoreRecordVo = new ScoreRecordVo();
		scoreRecordVo.setUserId(user.getId());
		scoreRecordVo.setIndex(index);
		scoreRecordVo.setLimit(limit);
		if(StringUtils.isNotBlank(optType)){
			scoreRecordVo.setOptType(optType);
		}
		//将字符串转换成时间
		if (StringUtils.isNotBlank(sTime)) {
			scoreRecordVo.setStartTime(DateUtils.getRealDate(DateUtils.convert(sTime, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
		}
		if (StringUtils.isNotBlank(eTime)) {
			scoreRecordVo.setEndTime(DateUtils.getFullDate(DateUtils.convert(eTime, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
		}
		PageInfo<ScoreRecordVo> pageInfo = scoreRecordService.listScoreRecord(scoreRecordVo);
		if(CollectionUtils.isNotEmpty(pageInfo.getPageList())){
			printJSON(new JsonMsg(1, "获取成功！", pageInfo));
		}else{
			printJSON(new JsonMsg(0, "数据为空！", pageInfo));
		}
	}
	
	/**
	 * 理财统计
	 * @return
	 */
	@RequestMapping(value="/statistics", method = RequestMethod.GET)
	public ModelAndView statistics(Model model){
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		if (user == null) {
			session.removeAttribute("frontUser");
			return new ModelAndView("/front/user/login");
		}
		UserAccount account1 = null ;
		HashMap<String,Integer> map = null ;
		if(user != null){
			account1 = accountService.getByUserId(user.getId());
			map = userAuthService.getUserAuthDetail(user.getId());
		}
		model.addAttribute("_account", account1);
		model.addAttribute("auth", map);
		UserAccount account=accountService.getByUserId(user.getId());
		FundDetailVo detail=tenderService.getFundDetailVo(user.getId());
		model.addAttribute("detail",detail);
		model.addAttribute("account",account);
		return new ModelAndView("/front/account/statistics");
	}

	/**
	 * 我要充值
	 * @return
	 */
	@RequestMapping(value="/recharge")
	public ModelAndView recharge(Model model,
				@RequestParam(value="index",required=false,defaultValue="1") int index,
				@RequestParam(value="limit",required=false,defaultValue="10") int limit,
				@RequestParam(value = "publishTimeBegin",required = false)String publishTimeBegin,
				@RequestParam(value = "publishTimeEnd",required = false)String publishTimeEnd,
				@RequestParam(value = "type",required = false,defaultValue="recharge")String type) throws Exception{
			User user = UserSession.get();
			user = userService.getById(user == null ?0:user.getId());
		if("recharge".equals(type)){
			UserAccount account=accountService.getByUserId(user.getId());
			model.addAttribute("user", user);
			model.addAttribute("account", account);	
		}
		if("records".equals(type)){
			if (user == null) {
			session.removeAttribute("_user");
			return new ModelAndView("/login");
			}
			RechargeRecordVo rechargeRecordVo = new RechargeRecordVo();
			rechargeRecordVo.setIndex(index);
			rechargeRecordVo.setLimit(limit);
			if (StringUtils.isNotBlank(publishTimeBegin)) {
				rechargeRecordVo.setPublishTimeStart(DateUtils.getRealDate(DateUtils.convert(publishTimeBegin, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			}
			if (StringUtils.isNotBlank(publishTimeEnd)) {
				rechargeRecordVo.setPublishTimeEnd(DateUtils.getFullDate(DateUtils.convert(publishTimeEnd, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			}
			rechargeRecordVo.setUserId(user.getId());
			PageInfo<RechargeRecordVo> pageInfo = rechargeService.listByMethod(rechargeRecordVo);
			model.addAttribute("publishTimeBegin", publishTimeBegin);
			model.addAttribute("publishTimeEnd", publishTimeEnd);
			model.addAttribute("pageInfo", pageInfo);
			model.addAttribute("total", pageInfo.getTotal());
		}
		model.addAttribute("type", type);
		return new ModelAndView("/front/account/recharge1");
	}
	
	/**
	 * 我要提现
	 * @return
	 */
	@RequestMapping(value="/withdraw")
	public ModelAndView withdraw(Model model,
					@RequestParam(value="index",required=false,defaultValue="1") int index,
					@RequestParam(value="limit",required=false,defaultValue="10") int limit,
					@RequestParam(value = "publishTimeBegin",required = false)String publishTimeBegin,
					@RequestParam(value = "publishTimeEnd",required = false)String publishTimeEnd,
					@RequestParam(value = "type",required = false,defaultValue="withdraw")String type,
					@RequestParam(value = "hidden",required=false,defaultValue="-1") int hidden) throws Exception{
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		if("withdraw".equals(type)){
			UserAccount account = accountService.getByUserId(user.getId());
			MemberLevel level=memberService.getById(account.getLevel());
			List<WithdrawRecord> recordList=withdrawService.listByDateAndUid(account.getUserId(), DateUtils.formatYearMonth(new Date()));
			//免提现手续费笔数
			model.addAttribute("count", (level.getCount()-recordList.size()>0)?(level.getCount()-recordList.size()):0);
			List<BankCard> cardList=bankCardService.listCardByUserId(user.getId());
			WithdrawRecordVo withdrawRecordVo = new WithdrawRecordVo();
			withdrawRecordVo.setUserId(user.getId());
			PageInfo<WithdrawRecordVo> pageInfo = withdrawService.listWithdrawByStatus(withdrawRecordVo);
			model.addAttribute("user", user);
			model.addAttribute("account", account);
			model.addAttribute("cardList",cardList);
			model.addAttribute("pageInfo", pageInfo);
			model.addAttribute("total", pageInfo.getTotal());
			
		}
		
		if("records".equals(type)){
			WithdrawRecordVo withdrawRecordVo = new WithdrawRecordVo();
			withdrawRecordVo.setIndex(index);
			withdrawRecordVo.setLimit(limit);
			if (StringUtils.isNotBlank(publishTimeBegin)) {
				withdrawRecordVo.setPublishTimeStart(DateUtils.getRealDate(DateUtils.convert(publishTimeBegin, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			}
			if (StringUtils.isNotBlank(publishTimeEnd)) {
				withdrawRecordVo.setPublishTimeEnd(DateUtils.getFullDate(DateUtils.convert(publishTimeEnd, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
			}
			withdrawRecordVo.setUserId(user.getId());
			PageInfo<WithdrawRecordVo> pageInfo = withdrawService.listWithdrawByStatus(withdrawRecordVo);
//			提现银行	提现账号	提现总额（元）	到账金额（元）	手续费（元）	提现时间	状态	操作	备注
			model.addAttribute("publishTimeBegin", publishTimeBegin);
			model.addAttribute("publishTimeEnd", publishTimeEnd);
			model.addAttribute("pageInfo", pageInfo);
			model.addAttribute("hidden", hidden);
			
			List<BankCard> bankList=bankCardService.listCardByUserId(user.getId());
			Bank bank=bankCardService.selectBackByCode(bankList.get(0).getBankName());
			model.addAttribute("bank", bank);
		}
		model.addAttribute("type", type);
		return new ModelAndView("/front/account/withdraw1");
	}
	
	/**
	 * 银行卡管理
	 * @return
	 */
	@RequestMapping(value="/card", method = RequestMethod.GET)
	public ModelAndView card(Model model){
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		if (user == null) {
			session.removeAttribute("_user");
			return new ModelAndView("/login");
		}
		UserAccount account1 = null ;
		HashMap<String,Integer> map = null ;
		if(user != null){
			account1 = accountService.getByUserId(user.getId());
			map = userAuthService.getUserAuthDetail(user.getId());
		}
		model.addAttribute("_account", account1);
		model.addAttribute("auth", map);
		BankCardVo bankCardVo = new BankCardVo();
		bankCardVo.setIndex(1);
		bankCardVo.setLimit(10);
		bankCardVo.setUserId(user.getId());
		PageInfo<BankCardVo> pageInfo = bankCardService.listAll(bankCardVo);
		model.addAttribute("pageInfo", pageInfo);
		//省级城市
		model.addAttribute("user", user);
		model.addAttribute("oneLevelCitys", cityService.cityList());
		model.addAttribute("bankMap", bankCardService.listBack());
		return new ModelAndView("/front/account/card");
	}
	
	/**
	 * 安全认证
	 * @return
	 */
	@RequestMapping(value="/safe", method = RequestMethod.GET)
	public ModelAndView safe(Model model){
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		if (user == null) {
			session.removeAttribute("_user");
			return new ModelAndView("/login");
		}
		//用户认证情况
		HashMap<String,Integer> authMap = userAuthService.getUserAuthDetail(user.getId());
		UserAuth userAuth = userAuthService.getAuthByUidAndType(user.getId(), "id5");
		UserAuth email = userAuthService.getAuthByUidAndType(user.getId(), "email");
		//用户银行卡
		BankCardVo bankCardVo = new BankCardVo();
		bankCardVo.setIndex(1);
		bankCardVo.setLimit(10);
		bankCardVo.setUserId(user.getId());
		PageInfo<BankCardVo> pageInfo = bankCardService.listAll(bankCardVo);
		model.addAttribute("user", user);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("total", pageInfo.getTotal());
		model.addAttribute("user", user);
		model.addAttribute("userAuth", userAuth);
		model.addAttribute("email", email);
		model.addAttribute("authMap", authMap);
		model.addAttribute("oneLevelCitys", cityService.getOneLevelCitys());
		model.addAttribute("bankMap", BaofuUtil.bankMap);
	
		return new ModelAndView("/front/account/safe1");
	}
	
	/**
	 * 修改登录密码
	 * @param oldPassword 原密码
	 * @param newPassword 新密码
	 * @throws Exception
	 */
	@RequestMapping(value="/password/update",method=RequestMethod.POST)
	public void updatePassword(@RequestParam String oldPassword,@RequestParam String newPassword) throws Exception{
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		if (user == null) {
			printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		if (StringUtils.isBlank(oldPassword)) {
			printJSON(new JsonMsg(2, "原密码不能为空！"));
			return;
		}
		if (StringUtils.isBlank(newPassword)) {
			printJSON(new JsonMsg(3, "新密码不能为空！"));
			return;
		}
		if (!user.getPassword().equals(MD5.GetMD5Code(oldPassword))) {
			printJSON(new JsonMsg(4, "原密码输入错误，请重新输入！"));
			return;
		}
		String hash=BaseUtil.randomHash();
		user.setPassword(MD5.GetMD5Code(MD5.GetMD5Code(newPassword)+hash));
		user.setPassword(SHA.encryptPassword(newPassword));
		Integer i = userService.saveOrUpdate(user);
		if (i>0) {
			printJSON(new JsonMsg(-1, "修改成功！"));
		}else{
			printJSON(new JsonMsg(0, "修改失败！"));
		}
	}
	
	private UserAuth getUserAuthByIdCard(String idCard){
		return  userAuthService.getUserAuthByIdCard(idCard);
	}
	
	/**
	 * 实名认证
	 * @param realname 真实姓名
	 * @param idCard 身份证号
	 * @throws Exception
	 */
	@RequestMapping(value="/setSafeVer",method=RequestMethod.POST)
	public void setSafeVer(@RequestParam String realname, @RequestParam String idCard) throws Exception{	
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		try {
			if (user == null) {
				printJSON(new JsonMsg(1, "请先登录！"));
				return;
			}
			if (StringUtils.isBlank(realname)) {
				printJSON(new JsonMsg(2, "请输入真实姓名！"));
				return;
			}
			if (StringUtils.isBlank(idCard)) {
				printJSON(new JsonMsg(3, "请输入身份证号！"));
				return;
			}
			//检查身份证号是否已存在
			UserAuth idCardAuth = getUserAuthByIdCard(idCard);
			if (idCardAuth != null && idCardAuth.getUserId().equals(user.getId())) {
				printJSON(new JsonMsg(4, "身份证号已存在！"));
				return;
			}
			user.setRealname(realname);
			userService.saveOrUpdate(user);
			//用户实名认证
			UserAuth userAuth = new UserAuth();
			userAuth.setUserId(user.getId());
			userAuth.setAuthType("id5");
			userAuth.setCreateTime(new Date());
			userAuth.setAuthTime(new Date());
			userAuth.setAuthName(idCard);
			Integer i=userAuthService.saveOrUpdateUserAuth(userAuth);
			//个人信息认证
/*			UserDetailInfoAuth userDetailInfoAuth = new UserDetailInfoAuth();
			userDetailInfoAuth.setUserId(user.getId());
			userDetailInfoAuth.setRealname(realname);
			userDetailInfoAuth.setIdCard(idCard);
			Integer i = userAuthService.saveOrUpdateUserDetailInfoAuth(userDetailInfoAuth);*/
			if (i > 0) {
				session.setAttribute("frontUser", user);
				printJSON(new JsonMsg(-1, "认证成功！",user));
			}else {
				printJSON(new JsonMsg(0, "认证失败！"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			printJSON(new JsonMsg(0, "系统异常,请稍后再试！"));
		}
	}
	
	/**
	 * 修改手机号码
	 * @param oldCode 原手机号验证码
	 * @param newPhone 新手机号码
	 * @param newCode 新手机号验证码
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/phone/update",method = RequestMethod.POST)
	public void updatePhone(@RequestParam(value="oldCode") String oldCode,
							  @RequestParam(value="newPhone") String newPhone,
							  @RequestParam(value="newCode") String newCode) throws Exception{
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		try {
			if(user == null){
				printJSON(new JsonMsg(1, "请先登录！"));
				return;
			}
			String session_old=(String) session.getAttribute("oldCode");
			if(StringUtils.isBlank(session_old)){
				printJSON(new JsonMsg(3, "系统暂时未检测到您发送的验证码"));
				return;
			}
			if(!session_old.equals(oldCode)){
				printJSON(new JsonMsg(4, "原手机号验证码错误"));
				return;
			}
			if(StringUtils.isBlank(newPhone)){
				printJSON(new JsonMsg(8, "新手机号不能为空"));
				return;
			}
			if(user.getPhone().equals(newPhone)){
				printJSON(new JsonMsg(9, "新手机号不能为原手机号"));
				return;			
			}
			User temp=userService.selectByNameOrPhone(newPhone);
			if(temp!=null){
				printJSON(new JsonMsg(10, "该手机号已注册"));
				return;
			}
			if(StringUtils.isBlank(newCode)){
				printJSON(new JsonMsg(11, "新手机号验证码不能为空"));
				return;
			}
			String session_new=(String) session.getAttribute("newCode");
			if(StringUtils.isBlank(session_new)){
				printJSON(new JsonMsg(12, "系统暂时未检测到您发送的验证码"));
				return;
			}else{
				if(!session_new.equals(newCode)){
					printJSON(new JsonMsg(13, "新手机号验证码错误"));
					return;						
				}
			}
			user.setPhone(newPhone);
			userService.saveOrUpdate(user);
			session.removeAttribute("newCode");
			session.removeAttribute("oldCode");
			printJSON(new JsonMsg(-1, "修改成功"));
		} catch (Exception e) {
			e.printStackTrace();
			printJSON(new JsonMsg(0, "系统异常,请稍后再试！"));
		}
	}
	
	/**
	 * 绑定邮箱
	 * @param email 邮箱号
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/email",method=RequestMethod.POST)
	public void ail(@RequestParam String email) throws Exception{
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		if(user == null){
			printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		if(StringUtils.isBlank(email)){
			printJSON(new JsonMsg(2, "邮箱不能为空！"));
			return;
		}
		try {
			Integer i=userService.saveOrUpdate(user);
			
			UserAuth auth=new UserAuth(user.getId(), "email", email);
			UserAuth authCheck = userAuthService.getAuthByUidAndType(user.getId(), "email");
			if(authCheck != null) {
				printJSON(new JsonMsg(3, "已进行过邮箱认证！"));
				return;
			}
			userAuthService.saveOrUpdateUserAuth(auth);
			
			if (i>0) {
				session.setAttribute("_user", user);
				printJSON(new JsonMsg(-1, "操作成功！"));
			}else{
				printJSON(new JsonMsg(0, "操作失败！"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			printJSON(new JsonMsg(0, "系统异常,请稍后再试！"));
		}
	}
	
	/**
	 * 站内信息
	 * @return
	 */
	@RequestMapping(value="/log", method = RequestMethod.GET)
	public ModelAndView log(){
		return new ModelAndView("/front/account/log");
	}
	
	/**
	 * 偿还贷款
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/loan")
	public ModelAndView loan(Model model,
							@RequestParam(value="index",required=false,defaultValue="1") int index,
							@RequestParam(value="limit",required=false,defaultValue="10") int limit,
							@RequestParam(value = "type",required = false,defaultValue="pay")String type,
							@RequestParam(value = "publishTimeBegin",required = false)String publishTimeBegin,
							@RequestParam(value = "publishTimeEnd",required = false)String publishTimeEnd,
							@RequestParam(value = "productId",required = false,defaultValue="-1") Integer productId) throws Exception{
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		BorrowTempVo borrow = new BorrowTempVo();
		borrow.setStatus(type);
		borrow.setUserId(user.getId());
		borrow.setIndex(index);
		borrow.setLimit(limit);
		if (StringUtils.isNotBlank(publishTimeBegin)) {
			borrow.setExpectPaymentDateBegin(DateUtils.getRealDate(DateUtils.convert(publishTimeBegin, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
		}
		if (StringUtils.isNotBlank(publishTimeEnd)) {
			borrow.setExpectPaymentDateEnd(DateUtils.getFullDate(DateUtils.convert(publishTimeEnd, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
		}
		if(productId != -1){
			borrow.setProductId(productId);
		}
		PageInfo<BorrowTempVo> pageInfo = borrowService.getBorrow(borrow);
		List<Product> listProduct = productService.productList();//产品列表
		model.addAttribute("listProduct", listProduct);
		model.addAttribute("publishTimeBegin", publishTimeBegin);
		model.addAttribute("publishTimeEnd", publishTimeEnd);
		model.addAttribute("productId", productId);
		model.addAttribute("type", type);
		model.addAttribute("pageInfo", pageInfo);
		return new ModelAndView("/front/account/loan1");
	}
	
	/**
	 * 基本资料
	 * @return
	 */
	@RequestMapping(value="/detail", method = RequestMethod.GET)
	public ModelAndView accountDetail(Model model){
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		
		UserAuth userAuth = userAuthService.getAuthByUidAndType(user.getId(), "id5");
		UserDetailInfoAuth userDetailInfoAuth = userAuthService.getUserDetailInfoAuthByUserId(user.getId());
		UserWorkInfoAuth userWorkInfoAuth = userAuthService.getUserWorkInfoAuthByUserId(user.getId());
		model.addAttribute("userDetailInfoAuth", userDetailInfoAuth);
		model.addAttribute("userWorkInfoAuth", userWorkInfoAuth);
		model.addAttribute("user", user);
		model.addAttribute("userAuth", userAuth);
		//省级城市
		model.addAttribute("oneLevelCitys", cityService.getOneLevelCitys());
		//省级下所有的市级
		if (userDetailInfoAuth != null) {
			City domiciliaryRegisterCity = new City();
			if (userDetailInfoAuth.getDomiciliaryRegisterCityId() != null) {
				domiciliaryRegisterCity.setPid(cityService.getCity(userDetailInfoAuth.getDomiciliaryRegisterCityId()).getPid());
			}
			List<City> domiciliaryRegisterCitys = cityService.listAll(domiciliaryRegisterCity);
			model.addAttribute("domiciliaryRegisterCitys", domiciliaryRegisterCitys);
			City liveCity = new City();
			if (userDetailInfoAuth.getLiveCityId() != null) {
				liveCity.setPid(cityService.getCity(userDetailInfoAuth.getLiveCityId()).getPid());
			}
			List<City> liveCitys = cityService.listAll(liveCity);
			model.addAttribute("liveCitys", liveCitys);
			//户籍地址
			if (userDetailInfoAuth.getDomiciliaryRegisterCityId() != null) {
				model.addAttribute("registerCity", cityService.getCity(userDetailInfoAuth.getDomiciliaryRegisterCityId()));
			}
			//居住城市
			if (userDetailInfoAuth.getLiveCityId() != null) {
				model.addAttribute("liveCity", cityService.getCity(userDetailInfoAuth.getLiveCityId()));
			}
		}
		if (userWorkInfoAuth != null) {
			City workCity = new City();
			if (userWorkInfoAuth.getWorkCityId() != null) {
				workCity.setPid(cityService.getCity(userWorkInfoAuth.getWorkCityId()).getPid());
			}
			List<City> workCitys = cityService.listAll(workCity);
			model.addAttribute("workCitys", workCitys);
			//工作城市
			if (userWorkInfoAuth.getWorkCityId() != null) {
				model.addAttribute("workCity", cityService.getCity(userWorkInfoAuth.getWorkCityId()));
			}
		}
		return new ModelAndView("/front/account/detail");
	}
	
	/**
	 * 我的借款
	 * @return
	 * @throws ParseException 
	 */
	@RequestMapping(value="/credit", method = RequestMethod.GET)
	public ModelAndView credit(Model model,
			@RequestParam(value="index",required=false,defaultValue="1") int index,
			@RequestParam(value="limit",required=false,defaultValue="10") int limit,
			@RequestParam(value = "publishTimeBegin",required = false)String publishTimeBegin,
			@RequestParam(value = "publishTimeEnd",required = false)String publishTimeEnd,
			@RequestParam(value = "status",required = false)String status,
			@RequestParam(value="timePeriod",required=false,defaultValue="-1")String timePeriod) throws ParseException{
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		UserAccount account1 = null ;
		HashMap<String,Integer> map = null ;
		if(user != null){
			account1 = accountService.getByUserId(user.getId());
			map = userAuthService.getUserAuthDetail(user.getId());
		}
		model.addAttribute("_account", account1);
		model.addAttribute("auth", map);
		BorrowTempVo borrow = new BorrowTempVo();
		borrow.setIndex(index);
		borrow.setLimit(limit);
		if(!"-1".equals(timePeriod)) {
			borrow.setTimePeriod(timePeriod);
			model.addAttribute("timePeriod", timePeriod);
		}
		if (StringUtils.isNotBlank(publishTimeBegin)) {
			borrow.setPublishTimeBegin(DateUtils.getRealDate(DateUtils.convert(publishTimeBegin, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
		}
		if (StringUtils.isNotBlank(publishTimeEnd)) {
			borrow.setPublishTimeEnd(DateUtils.getFullDate(DateUtils.convert(publishTimeEnd, DateUtils.YEAR_MOUTH_DAY_FORMAT)));
		}
		if (status != "") {
			borrow.setStatus(status);
			model.addAttribute("status", status);
		}
		model.addAttribute("publishTimeBegin", publishTimeBegin);
		model.addAttribute("publishTimeEnd", publishTimeEnd);
		borrow.setUserId(user.getId());
		PageInfo<BorrowTempVo> pageInfo = borrowService.getBorrow(borrow);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("total", pageInfo.getTotal());
		return new ModelAndView("/front/account/credit1");
	}
	
	/**
	 * 贷款统计
	 * @return
	 */
	@RequestMapping(value="/credit/statistics", method = RequestMethod.GET)
	public ModelAndView creditStatistics(Model model){
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		UserAccount account1 = null ;
		HashMap<String,Integer> map = null ;
		if(user != null){
			account1 = accountService.getByUserId(user.getId());
			map = userAuthService.getUserAuthDetail(user.getId());
		}
		model.addAttribute("_account", account1);
		model.addAttribute("auth", map);
		//金额汇总
		SumMoneyVo sumMoneyVo = borrowService.statisticByUserId(user.getId());
		model.addAttribute("sum", sumMoneyVo);
		//正常还清笔数统计
		SumMoneyVo number = borrowService.paymentNumber(user.getId());
		model.addAttribute("number", number);
		//平台待还笔数
		Integer num = tenderService.stayStillCount(user.getId());
		model.addAttribute("num", num);
		//待还管理费
		Double fee = borrowPaymentDetailService.selectFeeCount(user.getId());
		model.addAttribute("fee", fee);
		return new ModelAndView("/front/account/credit_statistics");
	}
	
	/**
	 * 还款计划
	 * @return
	 */
	@RequestMapping(value="/plan", method = RequestMethod.GET)
	public ModelAndView plan(Model model){
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		UserAccount account1 = null ;
		HashMap<String,Integer> map = null ;
		if(user != null){
			account1 = accountService.getByUserId(user.getId());
			map = userAuthService.getUserAuthDetail(user.getId());
		}
		model.addAttribute("_account", account1);
		model.addAttribute("auth", map);
		return new ModelAndView("/front/account/plan");
	}
	
	/**
	 * 检查开通第三方托管条件
	 * @param uid  用户id
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/reg/check",method=RequestMethod.POST)
	public String checkReg(@RequestParam("uid") Integer uid) throws Exception{
		try {
			User user=userService.getById(uid);
			UserAuth auth=userAuthService.getAuthByUidAndType(uid, "id5");
			if(auth==null){
				super.printJSON(new JsonMsg(1, "请先实名认证！"));
				return null;
			}
			super.printJSON(new JsonMsg(-1, "操作成功！"));
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 提现申请
	 * @return
	 */
	@RequestMapping(value="/withdraw/apply",method = RequestMethod.POST)
	public String withdrawApply(@RequestParam Double balance)throws Exception{
		try {
			User user = UserSession.get();
			user = userService.getById(user == null ?0:user.getId());
			if (user == null) {
				super.printJSON(new JsonMsg(1, "请先登陆"));
				return null;
			}
			if("N".equals(user.getFuionAccount())){
				super.printJSON(new JsonMsg(2, "请先开通账户托管，在申请提现！"));
			}
			if(balance==null){
				super.printJSON(new JsonMsg(3, "请输入提现金额"));
				return null;
			}
			if(balance < 100.0){
				super.printJSON(new JsonMsg(3, "提现金额必须大于100"));
				return null;
			}
			//查询金账户用户可用余额
			UserAccount accountFY = fuionAccountController.getFuionAccountBalance(user);
			if(accountFY.getBalance() < balance ){
				printJSON(new JsonMsg(4, "您的金账户可用余额为￥"+accountFY.getBalance()+"元,提现金额超过此金额,无法提现."));
				return null;
			}
			
			UserAccount account=accountService.getByUserId(user.getId());
			if(account.getBalance()<balance){
				super.printJSON(new JsonMsg(4, "您的迅泊达可用余额为￥"+account.getBalance()+"元,提现金额超过此金额，无法提现."));
				return null;				
			}
			List<BankCard> backList = bankCardService.listCardByUserId(user.getId());
			if(backList.isEmpty()){
				super.printJSON(new JsonMsg(5, "用户暂未绑定银行卡"));
				return null ; 
			}
			/*account.setFreezen(account.getFreezen()+balance);
			account.setBalance(account.getBalance()-balance);
			accountService.saveOrUpdate(account);*/
			super.printJSON(new JsonMsg(-1, "操作成功!"));
		} catch (Exception e) {
			e.printStackTrace();
			printJSON(new JsonMsg(0, "系统异常,请稍后再试！"));
		}
		return null;
	}
	
	/**
	 * 修改用户名
	 * @param user
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public String updateUserName(@ModelAttribute User user) throws Exception{
		if(user.getUsername()==null){
			super.printJSON(new JsonMsg(1, "用户修改名不能为空！"));
			return  null;
		}
		User userVo = frontUserService.selectByNameOrPhone(user.getUsername());
		if(userVo != null){
			super.printJSON(new JsonMsg(2, "该用户名以存在！"));
			return  null;
		}
		frontUserService.saveOrUpdate(user);
		super.printJSON(new JsonMsg(-1, "操作成功！"));
		return null;
	}
	/**
	 * 发布债权
	 * @param min 竞拍底价
	 * @param amount 债权总额
	 * @param date 截止时间
	 * @param id 投资记录id
	 * @return
	 */
	@RequestMapping(value="/change",method=RequestMethod.POST)
	public void changePublish(@RequestParam("min") Double min,
							  @RequestParam("amount") Double amount,
							  @RequestParam("date") String date,
							  @RequestParam("id") Integer id) throws Exception{
			User user = UserSession.get();
			user = userService.getById(user == null ?0:user.getId());
			try {
				if (user == null) {
					printJSON(new JsonMsg(1, "请先登录！"));
					return;
				}
				if(min==null){
					printJSON(new JsonMsg(2, "竞拍底价不能为空！"));
					return;
				}
				UserTender tender=tenderService.getById(id);

//				if(min<tender.getAwaitFund()*0.7){
//					printJSON(new JsonMsg(4, "竞拍底价不能少于待收金额(￥"+tender.getAwaitFund()+")的70%！"));
//					return;				
//				}
				
				if(StringUtils.isBlank(date)){
					printJSON(new JsonMsg(5, "截止时间不能为空！"));
					return;			
				}
				
				if(DateUtils.getDistanceTimeNum(new Date(), DateUtils.convert(date, "yyyy-MM-dd HH:mm:ss"))>0){
					printJSON(new JsonMsg(6, "截止时间不能小于当前时间！"));
					return;					
				}
				
				if(min>amount){
					printJSON(new JsonMsg(7, "竞拍底价不能大于债权总额!"));
					return;				
				}
				//用户投资的标是否已经发布债权转让
				Change change = changeService.getChangeByTenderIdAndBorrowId(tender.getBorrowId(), tender.getId());
				if (change != null) {
					//存在转让记录
					if(StringUtils.isNotBlank(change.getStatus()) &&"N".equals(change.getStatus())){
						Change change2 = new Change() ;  
						change2.setId(change.getId());
						change2.setStatus("T");
						change2.setMin(min);
						change2.setAmount(amount);
						change2.setMoney(min);
						change2.setIsCancel("N");
						change2.setOverdue(DateUtils.convert(date, "yyyy-MM-dd HH:mm:ss"));
						change2.setCreateTime(new Date());
						change2.setPeriod(tender.getPeriodTotal()-tender.getRecovedPeriod());
						change2.setTenderId(tender.getId());
						change2.setUserId(tender.getUserId());
						changeService.saveOrUpdateChange(change2);
						printJSON(new JsonMsg(-1, "操作成功!",change2.getId()));
						return;
					}
					printJSON(new JsonMsg(3, "债权已发布！"));
					return;				
				}
				Change change1 = new Change() ;  
				change1.setBorrowId(tender.getBorrowId());
				change1.setAmount(amount);
				change1.setCode(BaseUtil.generateCode(BaseUtil.ZHAIQUAN));
				change1.setCreateTime(new Date());
				change1.setIsCancel("N");
				change1.setMin(min);
				change1.setMoney(min);
				change1.setOverdue(DateUtils.convert(date, "yyyy-MM-dd HH:mm:ss"));
				change1.setStatus("T");
				change1.setValidDay(15);
				change1.setPeriod(tender.getPeriodTotal()-tender.getRecovedPeriod());
				change1.setTenderId(tender.getId());
				change1.setUserId(tender.getUserId());
				changeService.saveOrUpdateChange(change1);
				printJSON(new JsonMsg(-1, "操作成功!",change1.getId()));
			} catch (Exception e) {
				e.printStackTrace();
				printJSON(new JsonMsg(0, "系统异常,请稍后再试！"));
			}
	}
	
	@RequestMapping(value="/cnee", method=RequestMethod.POST)
	public void insertCnee(CneeInfo info) throws Exception{
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		if(StringUtils.isBlank(info.getName())){
			printJSON(new JsonMsg(5, "收货人姓名不能为空！"));
			return;			
		}
		if(StringUtils.isBlank(info.getAddress())){
			printJSON(new JsonMsg(5, "收货人地址不能为空！"));
			return;			
		}
		if(StringUtils.isBlank(info.getPhone())){
			printJSON(new JsonMsg(5, "收货人联系方式不能为空！"));
			return;			
		}
		info.setUserId(user.getId());
		cneeInfoServise.saveOrUpdate(info);
		printJSON(new JsonMsg(-1, "操作成功！"));
	}
	
	/**
	 * 邀请有奖
	 * @return
	 */
/*	@RequestMapping(value="/invite", method = RequestMethod.GET)
	public ModelAndView invite(Model model,
							   @RequestParam(value="type",required=false,defaultValue="invite") String type,	
							   @RequestParam(value="index",required=false,defaultValue="1") int index,
							   @RequestParam(value="limit",required=false,defaultValue="10") int limit){
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		if("invite_record".equals(type)){
			InviteRefVo inviteRefVo = new InviteRefVo();
			inviteRefVo.setIndex(index);
			inviteRefVo.setLimit(limit);
			inviteRefVo.setPid(user.getId());
			Integer count = frontUserService.getInviteCount(user.getId());
			inviteRefVo.setInvitedCount(count);
			model.addAttribute("inviteRefVo", inviteRefVo);
			PageInfo<InviteRefVo> pageInfo = frontUserService.listInviteRef(inviteRefVo);
			model.addAttribute("pageInfo", pageInfo);
			model.addAttribute("total", pageInfo.getTotal());
		}
		model.addAttribute("user", user);	
		model.addAttribute("type", type);
		return new ModelAndView("/front/account/invite1");
	}*/
	/**
	 * 体验金
	 * @return
	 */
	@RequestMapping(value="/vouch", method = RequestMethod.GET)
	public ModelAndView voucher(Model model){
 		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		UserAccount account1 = null ;
		HashMap<String,Integer> map = null ;
		if(user != null){
			account1 = accountService.getByUserId(user.getId());
			map = userAuthService.getUserAuthDetail(user.getId());
		}
		model.addAttribute("_account", account1);
		model.addAttribute("auth", map);
		return new ModelAndView("/front/account/vouchers");
	}
	
	/**
	 * 体验金
	 * @return
	 */
	/*@RequestMapping(value="/vouchers", method = RequestMethod.GET)
	public ModelAndView vouchers(){
		ModelAndView modelAndView = new ModelAndView();
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		if (user == null) {
			session.removeAttribute("frontUser");
			return new ModelAndView("/login");
		}
		AmountCoupon amountCoupon = new AmountCoupon();
		amountCoupon.setUserId(user.getId());
		int count = amountCouponService.count(amountCoupon);
		PageInfo<AmountCoupon> info = amountCouponService.list(amountCoupon);
		info.setTotal((count!=0?count:0));
		modelAndView.addObject("amountList", info);
		modelAndView.setViewName("/front/user/account/vouchers");
		return modelAndView;
	}*/
	
	/**
	 * 第三方开户页面
	 * @return
	 */
	@RequestMapping(value="/register",method=RequestMethod.GET)
	public ModelAndView reg(Model model){
		User user = UserSession.get();
		user = userService.getById(user.getId());
		model.addAttribute("user", user);
		/*List<BankCard> listCard = bankCardService.listCardByUserId(user.getId());
		if(listCard != null && listCard.size()>0) {
			BankCard bankCard = listCard.get(0);
			model.addAttribute("bankCard", bankCard);
		}*/
		
		return new ModelAndView("/front/account/register");
	}
	
	/*
	 * 绑定银行卡
	 */
	@RequestMapping(value="/bank/card",method=RequestMethod.POST)
	public void  flight_card() throws Exception{
		User user = UserSession.get();
		user = userService.getById(user == null ?0:user.getId());
		if(user == null){
			printJSON(new JsonMsg(1, "请先登录！"));
			return;
		}
		if("N".equals(user.getFuionAccount())){
			printJSON(new JsonMsg(2, "请先开通第三方托管账户！"));
			return;
		}
		printJSON(new JsonMsg(0, "第三方绑卡"));
	}
	
	@RequestMapping(value="/to/fuion",method=RequestMethod.GET)
	public ModelAndView toFuion(){
		return new ModelAndView("/front/account/fuion");
	}	
	
	/**
	 * 第三方注册页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/thirdRegister",method=RequestMethod.GET)
	public ModelAndView thirdRegister(Model model){
		Integer userId = UserSession.get().getId();
		User user = userService.getById(userId);
		List<Bank> banks = bankCardService.listBack();
		model.addAttribute("banks", banks);
		
		String oldUser = request.getParameter("oldUser");
		if(oldUser != null && "Y".equals(oldUser)) {//老用户删除银行卡
			bankCardService.deleteByUserId(userId);//删除银行卡
			userAuthService.deleteByUserId(userId);//删除用户所有认证
			//删除用户的支付密码和真实姓名
			user.setDealPassword("");
			user.setLoginPassword("");
			user.setRealname("");
			userService.saveOrUpdate(user);
		}
		model.addAttribute("next", 1);
		//实名认证
		UserAuth userAuth = authService.getAuthByUidAndType(userId, "id5");
		if(userAuth!=null){
			model.addAttribute("next", 2);
		}
		model.addAttribute("userAuth", userAuth);
		//银行卡绑定
		List<BankCard> bankCards = bankCardService.listCardByUserId(userId);
		BankCard bankCard = null;
		if(bankCards != null && bankCards.size()>0) {
			bankCard = bankCards.get(0);
			model.addAttribute("next", 3);
			//根据城市编码获取城市名称
			List<City> cityList = cityService.getCityAndPCityBYCode(bankCard.getCityCode());
			for(City city : cityList){
				if(-1==city.getPid()){
					model.addAttribute("province", city.getCode());
				}else{
					model.addAttribute("bankCityName", city.getName());
				}
			}
			model.addAttribute("city", bankCard.getCityCode());
		}
		model.addAttribute("bankCard", bankCard);

		
		
		if(StringUtils.isNotBlank(user.getLoginPassword()) && StringUtils.isNotBlank(user.getDealPassword())){
			model.addAttribute("next", 4);
		}
		model.addAttribute("user",user);
		
		return new ModelAndView("/front/account/thirdRegister");
	}
	
	@RequestMapping("/invite")
	public ModelAndView invite(Model model,
			@RequestParam(value = "index", required = false, defaultValue = "1") int index,
			@RequestParam(value = "limit", required = false, defaultValue = "10") int limit) {
		Integer Pid = UserSession.get().getId();
		InviteRefVo inviteVo = new InviteRefVo();
		inviteVo.setPid(Pid);
		inviteVo.setIndex(index);
		inviteVo.setLimit(limit);
		PageInfo<InviteRefVo> invoteInfo = inviteInfoservice.ListInviteInfo(inviteVo);
		model.addAttribute("invoteInfo", invoteInfo);
		// 获取推荐人信息
		User parentUser = userService.getById(Pid);
		if (parentUser != null) {
			model.addAttribute("parentUser", parentUser);
		}
		return new ModelAndView("/front/account/invite1");
	}
	
   /**
    * 
   * <p>Description:调转验证码页面 </p>
   * <p>Company:xbd </p>
   * @author:lilei
   * @date:2016年11月8日上午11:45:39
    */
	@RequestMapping("/invite/code")
	public ModelAndView inviteCode(Model model) {
		return new ModelAndView("/front/account/invite_code");
	}
	
	/**
	 * 
	* <p>Description:删除收货地址信息 </p>
	* <p>Company:xbd </p>
	* @author:lilei
	* @date:2017年1月20日上午8:54:25
	 */
	@RequestMapping(value="/cnee/delete",method=RequestMethod.POST)
	public void cneeInfoDelete(Integer cneeId) throws Exception{
		
		if (cneeId != null) {
			boolean result=cneeInfoServise.cneeDelete(cneeId);
			if(result){
				printJSON(new JsonMsg(-1, "删除成功!"));
			}else{
				printJSON(new JsonMsg(2, "删除失败!"));
			}
		}else{
				printJSON(new JsonMsg(1, "删除失败!"));
		}
	}
	
}